package com.example.service.impl;

import com.example.service.ExcelReader;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wangwenlong@dhcc.com.cn
 * @description:
 * @date 2023/11/24 20:34
 */

@Service
public class ExcelReaderImpl implements ExcelReader {

    public List<List<String>> readExcel(String fileName) throws IOException {
        List<List<String>> data = new ArrayList<>();
        Workbook workbook = new XSSFWorkbook(new FileInputStream(fileName));
        Sheet sheet = workbook.getSheetAt(0); // 读取第一个工作表

        for (int i = 0; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i); // 获取行对象
            if (row == null) {
                continue; // 跳过空行
            }

            List<String> rowData = new ArrayList<>(); // 存储行数据
            for (int j = 0; j < row.getLastCellNum(); j++) {
                Cell cell = row.getCell(j); // 获取单元格对象
                if (cell == null) {
                    rowData.add(""); // 跳过空单元格，添加空字符串
                } else {
                    String value = getCellValue(cell); // 获取单元格值
                    rowData.add(value);
                }
            }
            data.add(rowData); // 将行数据添加到结果列表中
        }
        workbook.close(); // 关闭工作簿对象
        return data; // 返回结果列表
    }

    private String getCellValue(Cell cell) {
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    return Double.valueOf(cell.getNumericCellValue()).toString();
                }
            case BOOLEAN:
                return Boolean.valueOf(cell.getBooleanCellValue()).toString();
            default:
                return ""; // 其他类型返回空字符串或自定义处理逻辑
        }
    }
}
